package com.corner.web.controller.byws;


import com.corner.common.annotation.RepeatSubmit;
import com.corner.common.config.CornerConfig;
import com.corner.common.core.controller.BaseController;
import com.corner.common.core.domain.AjaxResult;
import com.corner.common.core.domain.entity.SysUser;
import com.corner.common.core.domain.model.LoginUser;
import com.corner.common.core.page.TableDataInfo;
import com.corner.common.exception.GlobalException;
import com.corner.common.utils.DateUtils;
import com.corner.common.utils.StringUtils;
import com.corner.common.utils.file.FileUploadUtils;
import com.corner.common.utils.file.FileUtils;
import com.corner.common.utils.uuid.Seq;
import com.corner.framework.config.ServerConfig;
import com.corner.framework.web.service.TokenService;
import com.corner.system.domain.*;
import com.corner.system.domain.vo.EditUserInfoVo;
import com.corner.system.domain.vo.Operation;
import com.corner.system.domain.vo.transferQueryVo;
import com.corner.system.domain.vo.transferRepVo;
import com.corner.system.mapper.FarmerUserMapper;
import com.corner.system.mapper.SysUserMapper;
import com.corner.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

@RestController
@RequestMapping("/wushui")
@Slf4j
public class WushuiController extends BaseController {

    @Autowired
    private DeviceService deviceService;
    @Autowired
    private IoData_1Service ioData1Service;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SubsidyService subsidyService;
    @Autowired
    private SubsidyTempService subsidyTempService;
    @Autowired
    private ApprovalService approvalService;
    @Autowired
    private FarmerUserService farmerUserService;
    @Autowired
    private WorkOrderService workOrderService;
    @Autowired
    private FarmerUserMapper farmerUserMapper;
    @Autowired
    private TransferBatchesService transferBatchesService;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private WxgzhService wxgzhService;
    @Autowired
    private SysUserMapper userMapper;

    @Value("${spring.profiles.active}")
    public String profiles;

    /**
     * 获取用户设备列表
     * @return
     */
    @GetMapping("/getDeviceList")
    public AjaxResult getDeviceList(){
        LoginUser loginUser = tokenService.getLoginUser(request);
        String username = loginUser.getUsername();
        FarmerUser query = new FarmerUser();
        query.setTelephone(username);
        //根据用户登录手机号查询farmerUser
        List<FarmerUser> farmerUserList = farmerUserMapper.selectFarmerUser(query);
        List deviceList = new ArrayList();
        for(FarmerUser fu: farmerUserList){
            Long farmerId = fu.getFarmerId();
            // 根据farmerUserId查询设备
            List<Device> devices = deviceService.selectByFarmerId(farmerId);
            deviceList.addAll(devices);
        }

        //List<Device> devices = deviceService.selectByTel(username);
        return AjaxResult.success(deviceList);
    }


    /**
     * 获取设备近N个月的电量与电费情况
     * @param deviceId
     * @param selectCount
     * @return
     */
/*    @GetMapping("/getDataAndMonth")
    public AjaxResult getDataAndMonth(@RequestParam("deviceId") String deviceId,@RequestParam("selectCount") int selectCount){
        List<Map> dataAndMonth = ioData1Service.getDataAndMonth(deviceId,selectCount);
        return AjaxResult.success(dataAndMonth);
    }*/


    /**
     * 查询用户可领取红包补贴
     * @param subsidy
     * @return
     */
    @GetMapping("/selectUserSubsidyList")
    public AjaxResult selectUserSubsidyList(Subsidy subsidy) throws Exception {
        List<Subsidy> subsidyList = subsidyService.selectSubsidy(subsidy);
        return AjaxResult.success(subsidyList);
    }



    /**
     * 用户领取电费红包
     * @param requestVo
     * @return
     */
    /*@PostMapping("/getSubsidy")
    @RepeatSubmit
    public AjaxResult getSubsidy(@RequestBody SubsidyRequestVo requestVo)throws  Exception{
        subsidyService.getSubsidy(requestVo);
        return AjaxResult.success();
    }*/

    /**
     * 用户领取电费红包
     * @param subsidyList
     * @return
     */
    @PostMapping("/getSubsidy")
    @RepeatSubmit
    public AjaxResult getSubsidy(@RequestBody List<Subsidy> subsidyList)throws  Exception{
        if("dev".equals(profiles)){
            throw new GlobalException("测试环境无法领取补贴！");
        }
        String subsidy = subsidyService.getSubsidy(subsidyList);
        if(StringUtils.isBlank(subsidy)){
            subsidy = "领取成功！";
        }
        return AjaxResult.success(subsidy);
    }

    /**
     * 查询已申请补贴
     * @param deviceId
     * @return
     */
    @GetMapping("/querySubsidyByDeviceId")
    public TableDataInfo querySubsidyByDeviceId(String deviceId,String status)throws Exception{
        startPage();
        List<Subsidy> list = subsidyService.querySubsidyByDeviceId(deviceId,status);
        return getDataTable(list);
    }

    /**
     * 查询已领取成功补贴
     * @param deviceId
     * @return
     */
    @GetMapping("/querySuccessMoney")
    public AjaxResult querySuccessMoney(String deviceId)throws Exception{
        Map result = subsidyService.querySuccessMoney(deviceId);
        return AjaxResult.success(result);
    }

    /**
     * 批量审批补贴
     * @param subsidyTemps
     * @return
     */
    @PutMapping("/approvalBatch")
    public AjaxResult approvalBatch(@RequestBody List<SubsidyTemp> subsidyTemps){
        Long userId = tokenService.getLoginUser(request).getUserId();
        subsidyService.approvalBatch(subsidyTemps,userId);
        return AjaxResult.success();
    }

    /**
     * 确认审批全部
     * @param
     * @return
     */
    @PostMapping("/approvalAll/{operatorName}/{approvalId}")
    public AjaxResult approvalAll(@PathVariable("operatorName") String operatorName,@PathVariable("approvalId") Long approvalId){
        Long operationAccount = tokenService.getLoginUser(request).getUserId();
        String result = subsidyService.approvalAll(operationAccount,operatorName,approvalId);
        return AjaxResult.success(result);
    }

    /**
     * 修改单个设备审批标识
     * @param subsidyTemp
     * @return
     */
    @PutMapping("/changeApprovalFlag")
    public AjaxResult changeApprovalFlag(@RequestBody SubsidyTemp subsidyTemp){
        Long userId = tokenService.getLoginUser(request).getUserId();
        subsidyTemp.setOperationAccount(userId);
        subsidyService.changeApprovalFlag(subsidyTemp);
        return AjaxResult.success();
    }


    /**
     * 创建工单
     * @return
     */
    @PostMapping("/createWorkOrder")
    public AjaxResult createWorkOrder(){


        return AjaxResult.success();
    }

    /**
     * 查询待审批表单
     * @param
     * @return
     */
    @PreAuthorize("@ss.hasAnyRoles('user,admin')")
    @GetMapping("/selecPendingTable")
    public TableDataInfo selecPendingTable(SubsidyTemp subsidyTemp)throws Exception{
        startPage();
        List<SubsidyTemp> subsidyTemps = subsidyTempService.selectTempList(subsidyTemp);
        return getDataTable(subsidyTemps);
    }

    /**
     * 查询补贴列表
     * @param
     * @return
     */
    //@PreAuthorize("@ss.hasAnyRoles('user,admin')")
    @GetMapping("/selecSubsidyList")
    public TableDataInfo selecSubsidyList(Subsidy subsidy)throws Exception{
        startPage();
        List<Subsidy> subsidyList = subsidyService.selecSubsidyList(subsidy);
        return getDataTable(subsidyList);
    }


    /**
     * 查询审批统计数据
     * @param belongMonth
     * @return
     */
    @GetMapping("/getStatisticsData")
    public Map getStatisticsData(String belongMonth,Long approvalId)throws Exception{
        Map statisticsData = subsidyTempService.getStatisticsData(belongMonth,approvalId);
        return statisticsData;
    }


    /**
     * 根据id修改审批统计表
     * @param approval
     * @return
     */
    @PutMapping("/updateApprovalById")
    public AjaxResult updateApprovalById(@RequestBody Approval approval)throws Exception{
        approvalService.updateApprovalById(approval);
        return AjaxResult.success();
    }


    /**
     * 查询审批统计数据
     * @param approval
     * @return
     */
    @GetMapping("/getApprovalList")
    public TableDataInfo getApprovalList(Approval approval){
        startPage();
        List<Map> approvalList = approvalService.getApprovalList(approval);
        return getDataTable(approvalList);
    }


    /**
     * 用户提交工单
     * userInfo:{
     *  oldIDType:'1',//1身份证2户口簿
     *  oldName:'',
     *  oldNumber:'',
     *  newIDType:'1',
     *  newName:'',
     *  newNumber:'',
     *  newTel:'',.
     *  oldTel:'',
     *  newAddr:'',
     *  oldAddr:'',
     *  details:''
     * },
     * @return
     */
    @PostMapping("/applyWorkOrder")
    public AjaxResult applyWorkOrder(@RequestPart(value = "oldCard1",required = false)  MultipartFile oldCard1,
                                      @RequestPart(value = "oldCard2",required = false) MultipartFile oldCard2,
                                      @RequestPart(value = "oldBook",required = false) MultipartFile oldBook,
                                      @RequestPart(value = "newCard1",required = false) MultipartFile newCard1,
                                      @RequestPart(value = "newCard2",required = false) MultipartFile newCard2,
                                      @RequestPart(value = "newBook",required = false) MultipartFile newBook,
                                   @RequestPart("userInfo") @Validated Map userInfo){
        LoginUser loginUser = tokenService.getLoginUser(request);
        Long userId = loginUser.getUserId();
        userInfo.put("farmerId",userId);
        workOrderService.applyWorkOrder(oldCard1,oldCard2,oldBook,newCard1,newCard2,newBook,userInfo);
        return AjaxResult.success();
    }


    /**
     * 创建用户电话号
     * @param card1
     * @param card2
     * @param userInfo
     * @return
     */
    @RepeatSubmit
    @PostMapping("/changeTelOrder")
    public AjaxResult changeTelOrder(@RequestPart(value = "card1",required = false)  MultipartFile card1,
                                     @RequestPart(value = "card2",required = false) MultipartFile card2,
                                     @RequestPart("userInfo") @Validated Map userInfo) throws Exception{

        String wxcode = (String)userInfo.get("wxcode");
        Map<String, String> urlAccessToken = wxgzhService.getUrlAccessToken(wxcode,"");
        String openid = urlAccessToken.get("openid");
        if(openid == null){
            throw new GlobalException("无法获取OPENID");
        }
        //用户是否已关注公众号
        SysUser sysUser = userMapper.selectByOpenId(openid);
        if(sysUser == null ){
            System.out.println(openid);
            throw new GlobalException("请先关注公众号");
        }
        userInfo.put("openId",openid);

        workOrderService.createOrChangeTel(card1,card2,userInfo);
        return AjaxResult.success();
    }

    /**
     * 直接修改用户信息
     * @return
     */
    @PostMapping("/editUserInfo")
    public AjaxResult editUserInfo(@RequestBody EditUserInfoVo editUserInfoVo)throws Exception{
        SysUser user = tokenService.getLoginUser(request).getUser();
        farmerUserService.editUserInfo(editUserInfoVo, user);
        return AjaxResult.success();
    }




    /**
     * 查询操作工单
     * @return
     */
    @GetMapping("/selectWorkOrder")
    public TableDataInfo selectWorkOrder(Operation operation)throws Exception{

        String wxcode = operation.getWxcode();
        if(StringUtils.isNotBlank(wxcode)){
            Map<String, String> urlAccessToken = wxgzhService.getUrlAccessToken(wxcode,"");
            String openid = urlAccessToken.get("openid");
            if(openid == null){
                throw new GlobalException("无法获取OPENID");
            }
            //用户是否已关注公众号
            SysUser sysUser = userMapper.selectByOpenId(openid);
            if(sysUser == null ){
                System.out.println(openid);
                throw new GlobalException("请先关注公众号");
            }
            operation.setOpenId(openid);

        }
        startPage();
        List<Operation> operations = workOrderService.selectWorkOrder(operation);
        return getDataTable(operations);
    }


    /**
     * 审批工单,同时修改用户信息
     * @return
     */
    @PostMapping("/approvalWorkOrder")
    public AjaxResult approvalWorkOrder(@RequestBody Operation operation)throws Exception{
        SysUser user = tokenService.getLoginUser(request).getUser();
        operation.setOperatorId(user.getUserId());
        operation.setOperatorName(user.getUserName());
        workOrderService.approvalWorkOrder(operation);
        return AjaxResult.success();
    }

    /**
     * 审批工单,不修改用户信息
     * @return
     */
    @PostMapping("/approvalWorkOrderNoEdit")
    public AjaxResult approvalWorkOrderNoEdit(@RequestBody Operation operation)throws Exception{
        SysUser user = tokenService.getLoginUser(request).getUser();
        operation.setOperatorId(user.getUserId());
        operation.setOperatorName(user.getUserName());
        workOrderService.approvalWorkOrderNoEdit(operation);
        return AjaxResult.success();
    }
    /**
     * 查询农户列表
     * @param farmerUser
     * @return
     */
    @GetMapping("/listFarmerUser")
    public TableDataInfo listFarmerUser(FarmerUser farmerUser){
        startPage();
        List<FarmerUser> farmerUsers = farmerUserService.selectFarmerUser(farmerUser);
        return getDataTable(farmerUsers);
    }

    /**
     * 根据id查询农户信息
     * @param farmerId
     * @return
     */
    @GetMapping("/selectFarmerUserDetail")
    public AjaxResult selectFarmerUserDetail(Long farmerId){
        FarmerUser farmerUsers = farmerUserService.selectFarmerUserDetail(farmerId);
        return AjaxResult.success(farmerUsers);
    }

    /**
     * 根据父地址查询子地址
     * @param parentAddr
     * @return
     */
    @GetMapping("/selectAddrByParent")
    public AjaxResult selectAddrByParent(String parentAddr){
        List<Map> maps = farmerUserMapper.selectAddrByParent(parentAddr);
        return AjaxResult.success(maps);
    }

    /**
     * 根据地址id查询地址信息
     * @param addrId
     * @return
     */
    @GetMapping("/selectAddrById")
    public AjaxResult selectAddrById(String addrId){
        Map addr = farmerUserMapper.selectAddrById(addrId);
        return AjaxResult.success(addr);
    }


    /**
     * 查询用户操作日志
     * @param farmerUserId
     * @return
     */
    @GetMapping("/selectUserOperationLogs")
    public AjaxResult selectUserOperationLogs(Long farmerUserId){
        List<OperationLog> operationLogs = farmerUserService.selectUserOperationLogs(farmerUserId);
        return AjaxResult.success(operationLogs);
    }


    /**
     * 修改手机号
     * @param query
     * @return
     */
    @PutMapping("/changeFamerUserTel")
    public AjaxResult changeFamerUserTel(@RequestBody Map query)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        SysUser user = loginUser.getUser();
        query.put("userId",user.getUserId());
        query.put("telephone",user.getUserName());
        farmerUserService.changeFamerUserTel(query);

        //3、刷新缓存信息
        String newTel = (String)query.get("newtel");//新手机号

        LoginUser loginUserNew = new LoginUser();
        user.setTelephoneNumber(newTel);
        user.setUserName(newTel);
        loginUserNew.setLoginTime(new Date().getTime());
        loginUserNew.setUser(user);

        tokenService.refreshToken(loginUser);
        return AjaxResult.success(loginUser);
    }


    /**
     * 查询补贴领取以及转账状态
     * @param query
     * @return
     */
    @GetMapping("/selectTransferDetails")
    public TableDataInfo selectTransferDetails(transferQueryVo query)throws Exception{
        startPage();
        List<transferRepVo> list = subsidyService.selectTransferDetails(query);
        return getDataTable(list);
    }

    /**
     * 查询转账记录
     * @param query
     * @return
     */
    @GetMapping("/selectTransferBatches")
    public TableDataInfo selectTransferBatches(transferQueryVo query)throws Exception{
        startPage();
        List<transferRepVo> list = transferBatchesService.selectTransferBatches(query);
        Map<String, Integer> statistics = transferBatchesService.selectTransferBatchesStatistics(query);
        return getDataTableStatistics(list,statistics);
    }

    /**
     * 获取修改手机号初始页面数据
     * @param
     * @return
     */
    @GetMapping("/getEditChangeTelPage")
    public AjaxResult getEditChangeTelPage()throws Exception{

        Map result = workOrderService.getEditChangeTelPage();
        return AjaxResult.success(result);
    }



}






